package org.marsdonne.sync.messenger.artemis;

import org.marsdonne.sync.Event;
import org.marsdonne.sync.Syncable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.Set;

public class SyncImpl implements Syncable {

    @Value("${sync.artemis.channel:channels.sync}")
    private String channel;

    @Resource(name = "syncJmsTemplate")
    private JmsTemplate syncJmsTemplate;

    @Override
    public void sync(Event event) {
        Set<ConstraintViolation<Event>> violations = event.validate();

        if(violations.isEmpty()) {
            syncJmsTemplate.send(channel, session -> session.createObjectMessage(event));
        } else {
            StringBuilder errorsBuilder = new StringBuilder();
            for (ConstraintViolation<Event> violation : violations) {
                errorsBuilder.append(violation.getMessage() + "\n");
            }
            throw new RuntimeException(errorsBuilder.toString());
        }
    }
}
